//
//  AppDelegate.m
//  AAIM
//
//  Created by awh on 2019/11/22.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import <CloudPushSDK/CloudPushSDK.h>
#import <UserNotifications/UserNotifications.h>
#import <Bugly/Bugly.h>
@interface AppDelegate () <UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate
{
    // iOS 10通知中心
    UNUserNotificationCenter *_notificationCenter;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self getAppConfigur];
    [Bugly startWithAppId:@"9d93defba2"];
    // APNs注册，获取deviceToken并上报
    [self registerAPNS:application];
    //推送
    [self initCloudPush];
    [self listenerOnChannelOpened];
    // 监听推送消息到达
    [self registerMessageReceive];
    // 点击通知将App从关闭状态启动时，将通知打开回执上报
    // [CloudPushSDK handleLaunching:launchOptions];(Deprecated from v1.8.1)
    [CloudPushSDK sendNotificationAck:launchOptions];
    [[ChatTool shareChatTool] requestSeverTime];//服务器时间

    [[LoginManager shareLoginManager] loginMethod];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    self.window.backgroundColor = [UIColor whiteColor];
    
    NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"沙盒地址：%@", doucument);
    
    return YES;
}
-(void)initCloudPush {
    // SDK初始化
    [CloudPushSDK asyncInit:@"28310275" appSecret:@"f765d2a692a8fa6a15b2ed0e393a9deb" callback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"Push SDK init success, deviceId: %@", [CloudPushSDK getDeviceId]);
        } else {
            NSLog(@"Push SDK init failed, error: %@", res.error);
        }
    }];
}
/**
 *    注册苹果推送，获取deviceToken用于推送
 *
 *    @param     application
 */
- (void)registerAPNS:(UIApplication *)application {
    float systemVersionNum = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersionNum >= 10.0) {
        // iOS 10 notifications
        _notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
        // 创建category，并注册到通知中心
        [self createCustomNotificationCategory];
        _notificationCenter.delegate = self;
        // 请求推送权限
        [_notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // granted
                NSLog(@"User authored notification.");
                // 向APNs注册，获取deviceToken
                dispatch_async(dispatch_get_main_queue(), ^{
                    [application registerForRemoteNotifications];
                });
            } else {
                // not granted
                NSLog(@"User denied notification.");
            }
        }];
    } else if (systemVersionNum >= 8.0) {
        // iOS 8 Notifications
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        [application registerUserNotificationSettings:
         [UIUserNotificationSettings settingsForTypes:
          (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                           categories:nil]];
        [application registerForRemoteNotifications];
#pragma clang diagnostic pop
    } else {
        // iOS < 8 Notifications
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
#pragma clang diagnostic pop
    }
}
/*
 *  苹果推送注册成功回调，将苹果返回的deviceToken上传到CloudPush服务器
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
        if (res.success) {
            NSLog(@"Register deviceToken success, deviceToken: %@", [CloudPushSDK getApnsDeviceToken]);

        } else {
            NSLog(@"Register deviceToken failed, error: %@", res.error);
        }
    }];
}
/**
 *  创建并注册通知category(iOS 10+)
 */
- (void)createCustomNotificationCategory {
    // 自定义`action1`和`action2`
    UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"test1" options: UNNotificationActionOptionNone];
    UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action2" title:@"test2" options: UNNotificationActionOptionNone];
    // 创建id为`test_category`的category，并注册两个action到category
    // UNNotificationCategoryOptionCustomDismissAction表明可以触发通知的dismiss回调
    UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"test_category" actions:@[action1, action2] intentIdentifiers:@[] options:
                                        UNNotificationCategoryOptionCustomDismissAction];
    // 注册category到通知中心
    [_notificationCenter setNotificationCategories:[NSSet setWithObjects:category, nil]];
}
/*
 *  苹果推送注册失败回调
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError %@", error);
}

#pragma mark Channel Opened
/**
 *    注册推送通道打开监听
 */
- (void)listenerOnChannelOpened {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onChannelOpened:)
                                                 name:@"CCPDidChannelConnectedSuccess"
                                               object:nil];
}

/**
 *    推送通道打开回调
 *
 *    @param     notification
 */
- (void)onChannelOpened:(NSNotification *)notification {
    NSLog(@"温馨提示=====消息通道建立成功");
}


#pragma mark- 推送消息到来监听；
/**
 *    注册推送消息到来监听
 */
- (void)registerMessageReceive {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onMessageReceived:)
                                                 name:@"CCPDidReceiveMessageNotification"
                                               object:nil];
}
/**
 *    处理到来推送消息
 *
 *    @param     notification
 */
- (void)onMessageReceived:(NSNotification *)notification {
    CCPSysMessage *message = [notification object];
    NSString *title = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding];
    NSString *body = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding];
    NSLog(@"Receive message title: %@, content: %@.", title, body);
}
#pragma mark- 通知打开监听：
/*
 *  App处于启动状态时，通知打开回调
 */
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo {
    NSLog(@"Receive one notification.");
    // 取得APNS通知内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    // 内容
    NSString *content = [aps valueForKey:@"alert"];
    // badge数量
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
    // 播放声音
    NSString *sound = [aps valueForKey:@"sound"];
    // 取得Extras字段内容
    NSString *Extras = [userInfo valueForKey:@"Extras"]; //服务端中Extras字段，key是自己定义的
    NSLog(@"content = [%@], badge = [%ld], sound = [%@], Extras = [%@]", content, (long)badge, sound, Extras);
    // iOS badge 清0
    application.applicationIconBadgeNumber = 0;
    // 通知打开回执上报
    // [CloudPushSDK handleReceiveRemoteNotification:userInfo];(Deprecated from v1.8.1)
    [CloudPushSDK sendNotificationAck:userInfo];
}

#pragma mark- 初始化数据
- (void)getAppConfigur{
    [LoginRequestLogic getAppInfoUrlwithSuccess:^(NSDictionary * _Nonnull Dict) {
//              NSLog(@"app信息：%@",Dict);
        if ([Dict[@"code"] integerValue] == 200) {
            NSArray * dataAry = Dict[@"data"][@"configs"];
            if (dataAry.count>0) {

                for (NSDictionary * dic in dataAry) {
                    if ([dic[@"name"] isEqualToString:@"头像地址"]) {
                      [[NSUserDefaults standardUserDefaults] setValue:dic[@"values"] forKey:@"userHeaderImage"];
                    }
                    if ([dic[@"name"] isEqualToString:@"二维码地址"]) {
                       [[NSUserDefaults standardUserDefaults] setValue:dic[@"values"] forKey:@"userInfoImage"];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"service"]) {
                       [[NSUserDefaults standardUserDefaults] setValue:dic[@"values"] forKey:@"kefuQRCode"];
                        [[NSUserDefaults standardUserDefaults] setValue:dic[@"name"] forKey:@"kefuWechat"];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"isVcode"]) {
                       [[NSUserDefaults standardUserDefaults] setValue:dic[@"values"] forKey:@"isVcode"];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"head"]) {
                        [CacheTool saveUserDefaults:@"APP_USER_HEAD_KEY" dataObj:[NSString stringWithFormat:@"%@",dic[@"values"]]];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"qr"]) {
                        [CacheTool saveUserDefaults:@"APP_USER_QR_KEY" dataObj:[NSString stringWithFormat:@"%@",dic[@"values"]]];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"service"]) {
                        [CacheTool saveUserDefaults:@"APP_USER_SERVICE_KEY" dataObj:[NSString stringWithFormat:@"%@",dic[@"values"]]];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"voice"]) {
                        [CacheTool saveUserDefaults:@"APP_USER_VOICE_KEY" dataObj:[NSString stringWithFormat:@"%@",dic[@"values"]]];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"pic"]) {
                        [CacheTool saveUserDefaults:@"APP_USER_PIC_KEY" dataObj:[NSString stringWithFormat:@"%@",dic[@"values"]]];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"isVcode"]) {
                        [CacheTool saveUserDefaults:@"APP_USER_ISVCODE_KEY" dataObj:[NSString stringWithFormat:@"%@",dic[@"values"]]];
                    }
                    
                    if ([dic[@"attribute"] isEqualToString:@"socket"]) {
                        [CacheTool saveUserDefaults:@"APP_USER_SOCKET_KEY" dataObj:[NSString stringWithFormat:@"%@",dic[@"values"]]];
                    }
                    if ([dic[@"attribute"] isEqualToString:@"port"]) {
                        [CacheTool saveUserDefaults:@"APP_USER_PORT_KEY" dataObj:[NSString stringWithFormat:@"%@",dic[@"values"]]];
                    }
                }
                [[NSUserDefaults standardUserDefaults] setValue:Dict[@"data"][@"url"] forKey:@"quotesUrl"];
                [[NSUserDefaults standardUserDefaults] setValue:Dict[@"data"][@"version"] forKey:@"appVersion"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        
        }
    } failure:^(NSString * _Nonnull errMsg) {
        NSLog(@"请求配置失败");
    }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[LiftIMClient sharedClient] closeConnect];
    NSLog(@"后台后台后台关闭socket");
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {

    [[LiftIMClient sharedClient] reconnet];
    NSLog(@"进入前台=开启socket");

    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
